package com.lzm.ydpt.module.mall.activity;

import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.ViewPager;

import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonutils.WebUtil;
import com.byt.framlib.commonutils.image.ImageLoaderUtils;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.LoadingTip;
import com.byt.framlib.commonwidget.NoScrollWebView;
import com.byt.framlib.commonwidget.ObservableScrollView;
import com.byt.framlib.commonwidget.badgeview.QBadgeView;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.byt.framlib.commonwidget.refresh.RefreshHeaderView;
import com.byt.framlib.imagePager.BigImagePagerActivity;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.Dapplication;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.mall.CartNumBus;
import com.lzm.ydpt.entity.mall.GoodsOption;
import com.lzm.ydpt.entity.mall.ProductBean;
import com.lzm.ydpt.entity.mall.ProductCartBus;
import com.lzm.ydpt.entity.mall.ProductDetailsBus;
import com.lzm.ydpt.entity.mall.ShopGoods;
import com.lzm.ydpt.entity.mall.SpecBean;
import com.lzm.ydpt.module.mall.adapter.VideoPagerAdapter;
import com.lzm.ydpt.module.mall.dialog.SkuBottomDialog;
import com.lzm.ydpt.module.mall.utils.ProductUtil;
import com.lzm.ydpt.module.mall.view.MallViewPager;
import com.lzm.ydpt.mvp.contract.ProductDetailsContract;
import com.lzm.ydpt.mvp.presenterimpl.ProductDetailsPresenterImpl;
import com.lzm.ydpt.utils.MessageCountUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 商品详情
 */
public class ProductDetailsActivity extends BaseActivity<ProductDetailsPresenterImpl> implements ProductDetailsContract.View, SkuBottomDialog.SureClickCall {

    @BindView(R.id.ltip_product_details)
    LoadingTip ltip_product_details;

    @BindView(R.id.srf_pull_product_data)
    SmartRefreshLayout srf_pull_product_data;
    @BindView(R.id.sv_product_details)
    ObservableScrollView sv_product_details;
    @BindView(R.id.ll_product_head_data)
    LinearLayout ll_product_head_data;

    @BindView(R.id.vp_product_pic)
    MallViewPager vp_product_pic;
    @BindView(R.id.tv_icon_num_f)
    TextView tv_icon_num_f;
    @BindView(R.id.tv_icon_num_s)
    TextView tv_icon_num_s;

    @BindView(R.id.tv_show_price_symbol)
    TextView tv_show_price_symbol;
    @BindView(R.id.tv_product_detail_price)
    TextView tv_product_detail_price;

    @BindView(R.id.tv_product_name)
    TextView tv_product_name;
    @BindView(R.id.tv_product_desc)
    TextView tv_product_desc;

    @BindView(R.id.ll_shop_product_collect)
    LinearLayout ll_shop_product_collect;
    @BindView(R.id.web_product_details)
    NoScrollWebView web_product_details;

    @BindView(R.id.tv_cart_num)
    TextView tv_cart_num;
    @BindView(R.id.img_product_cart)
    ImageView img_product_cart;
    @BindView(R.id.img_shop_product_collect)
    ImageView img_shop_product_collect;
    @BindView(R.id.tv_shop_product_collect)
    TextView tv_shop_product_collect;
    @BindView(R.id.ll_product_store)
    LinearLayout ll_product_store;

    private int currentPosition = 0;
    private List<View> viewList = new ArrayList<>();

    private ProductBean mProductBean = null;
    private List<String> tempList = new ArrayList<>();

    private SkuBottomDialog mBottomSheetDialog;
    private long goods_id = 0L;
    private ShopGoods selectGoods;
    private int selectNum = 1;
    private GoodsOption mGoodsoption = null;

    private QBadgeView cartBadgeView;
    private int headHeight;

    @Override
    public int getLayoutId() {
        return R.layout.activity_mall_product_details;
    }

    @Override
    public ProductDetailsPresenterImpl initPreData() {
        return new ProductDetailsPresenterImpl(this);
    }

    @Override
    public void initView() {
        goods_id = getIntent().getLongExtra(Constants.INP_PRODUCT_ID, 0L);
        initTitle();
        initAdapter();
        initWeb();
        setRefresh();
        ltip_product_details.setLoadingTip(LoadingTip.LoadStatus.loading);
        fetchProductinfo();
        fetchSkuData();
        addSubscription(RxBus.getDefault().toObservable(ProductDetailsBus.class)
                .subscribe(event -> {
                    fetchProductinfo();
                }));
        addSubscription(RxBus.getDefault().toObservableSticky(CartNumBus.class).subscribe(cartNumBus -> {
            if (cartNumBus != null) {
                setCartNum(cartNumBus.getCart_num());
            }
        }));
        setCartNum(MessageCountUtil.getInstance().get(1, String.valueOf(Dapplication.getUserInfo().getMemberId()), ""));
    }

    private void initTitle() {

    }

    private void setRefresh() {
        setRefreshLayout(srf_pull_product_data);
        srf_pull_product_data.setEnableLoadMore(false);
        srf_pull_product_data.setEnableRefresh(true);
        srf_pull_product_data.setRefreshHeader(new RefreshHeaderView(mBContext).getHeaderStyleStaffF4());
        srf_pull_product_data.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                fetchProductinfo();
            }
        });
        // 获取顶部高度后，设置滚动监听
        ViewTreeObserver vto = ll_product_head_data.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ll_product_head_data.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                headHeight = ll_product_head_data.getHeight();
            }
        });
    }

    private void setCartNum(int num) {
        if (cartBadgeView == null) {
            cartBadgeView = new QBadgeView(this);
            cartBadgeView.bindTarget(img_product_cart)
                    .setBadgeTextSize(8, true)
                    .setBadgeGravity(Gravity.END | Gravity.TOP);
        }
        cartBadgeView.setBadgeNumber(num);
    }

    /**
     * 获取商品属性
     */
    private void fetchSkuData() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("goods_id", goods_id);
        mPresenter.onProductOption(formBodys.build());
    }

    private void initWeb() {
        WebSettings webSettings = web_product_details.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        web_product_details.clearCache(true);
        web_product_details.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        web_product_details.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            web_product_details.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    private void fetchProductinfo() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("id", 0);
        formBodys.add("goods_id", goods_id);
        mPresenter.onProductDetails(formBodys.build());
    }

    private void initAdapter() {

    }

    private void initProductData() {
        initHeadImage();
        tv_product_name.setText(mProductBean.getTitle());
        if (TextUtils.isEmpty(mProductBean.getFunctional_indications())) {
            tv_product_desc.setVisibility(View.GONE);
        } else {
            tv_product_desc.setVisibility(View.VISIBLE);
            tv_product_desc.setText(mProductBean.getFunctional_indications());
        }
        if (!TextUtils.isEmpty(mProductBean.getMin_price()) && ProductUtil.pausePrice(mProductBean.getMin_price()) > 0) {
            tv_show_price_symbol.setVisibility(View.VISIBLE);
            if (ProductUtil.pausePrice(mProductBean.getMax_price()) > 0 && !mProductBean.getMax_price().equals(mProductBean.getMin_price())) {
                tv_product_detail_price.setText(mProductBean.getMin_price() + "~" + mProductBean.getMax_price());
            } else {
                tv_product_detail_price.setText(mProductBean.getMin_price() + "");
            }
        } else {
            tv_show_price_symbol.setVisibility(View.GONE);
            tv_product_detail_price.setVisibility(View.GONE);
        }

        if (mProductBean.getGift_flag() == 1) {
            ll_product_store.setVisibility(View.GONE);
        } else {
            ll_product_store.setVisibility(View.VISIBLE);
        }
        img_shop_product_collect.setSelected(mProductBean.getCollection_flag() == 1);

        // 获取顶部高度后，设置滚动监听
        ViewTreeObserver vto = ll_product_head_data.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ll_product_head_data.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                headHeight = ll_product_head_data.getHeight();
            }
        });
        if (!TextUtils.isEmpty(mProductBean.getContent())) {
            web_product_details.setVisibility(View.VISIBLE);
            web_product_details.loadDataWithBaseURL(null, WebUtil.getHtmlData(mProductBean.getContent()), "text/html", "utf-8", null);
            web_product_details.getSettings().setJavaScriptEnabled(true);
        } else {
            web_product_details.setVisibility(View.GONE);
        }
    }

    private void initHeadImage() {
        if (mProductBean.getBanner_images_src() != null && mProductBean.getBanner_images_src().size() > 0) {
            viewList.clear();
            tempList.clear();
            tempList.addAll(mProductBean.getBanner_images_src());
            if (!TextUtils.isEmpty(mProductBean.getVideo_src())) {
                tempList.add(0, mProductBean.getVideo_src());
            }
            int size = tempList.size();
            for (int i = 0; i < size; i++) {
                ImageView imageView = new ImageView(mBContext);
                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                ImageLoaderUtils.display(imageView, tempList.get(i));
                viewList.add(imageView);
                imageView.setTag(i);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();
                        if (!TextUtils.isEmpty(mProductBean.getVideo_src())) {
                            position--;
                        }
                        BigImagePagerActivity.startImagePagerActivity(mBContext, mProductBean.getBanner_images_src(), position);
                    }
                });
            }
            VideoPagerAdapter videoPagerAdapter = new VideoPagerAdapter(mBContext, viewList);
            vp_product_pic.setAdapter(videoPagerAdapter);
            vp_product_pic.setOffscreenPageLimit(tempList.size());
            vp_product_pic.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float v, int i1) {

                }

                @Override
                public void onPageSelected(int position) {
                    currentPosition = position;
                    tv_icon_num_f.setText((position + 1) + "");
                    tv_icon_num_s.setText("/" + tempList.size());
                }

                @Override
                public void onPageScrollStateChanged(int i) {

                }
            });
            vp_product_pic.setCurrentItem(currentPosition);
            tv_icon_num_f.setText((currentPosition + 1) + "");
            tv_icon_num_s.setText("/" + tempList.size());
        }
    }

    public void setSkuText() {
        //已选 刷新界面

    }

    private void bottomDismiss() {
        mBottomSheetDialog.dismiss();
    }

    @OnClick({R.id.img_product_details_back, R.id.rl_product_cart, R.id.ll_customer_service, R.id.ll_shop_product_collect, R.id.tv_add_product_cart, R.id.tv_shop_product_buy})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {
            return;
        }
        switch (view.getId()) {
            case R.id.img_product_details_back:
                finish();
                break;
            case R.id.rl_product_cart:
                Bundle bundle = new Bundle();
                openActivity(MallMainActivity.class, bundle);
                break;
            case R.id.ll_customer_service:
                showShortToast("客服");
                break;
            case R.id.ll_shop_product_collect:
                putProductCollect();
                break;
            case R.id.tv_add_product_cart:
                showBottomSheetDialog(2);
                break;
            case R.id.tv_shop_product_buy:
                showBottomSheetDialog(3);
                break;
        }
    }

    /**
     * 收藏商品
     */
    private void putProductCollect() {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("goods_id", goods_id);
        mPresenter.onCollectionProduct(formBodys.build());
    }

    /**
     * 加入购物车
     */
    private void postCartProduct() {
        startProgressDialog();
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("option_id", selectGoods.getOption_id());
        formBodys.add("quantity", selectNum);
        mPresenter.onAddCartProduct(formBodys.build());
    }

    /**
     * 提交订单
     */
    private void postToOrder() {
        bottomDismiss();
        Bundle bundle = new Bundle();
        List<ShopGoods> tempList = new ArrayList<>();
        tempList.add(selectGoods);
        String goodsRequest = ProductUtil.goodRequestData(tempList);
//        bundle.putString(FillOrderActivity.INP_ORDER_PRODUCT_LIST, goodsRequest);
//        openActivity(FillOrderActivity.class, bundle);
    }

    /**
     * 展示dialog
     */
    public void showBottomSheetDialog(int showType) {
        if (mGoodsoption == null) {
            showShortToast("sku数据属性未加载出来");
            return;
        }
        if (mBottomSheetDialog == null) {
            mBottomSheetDialog = new SkuBottomDialog(mBContext, mGoodsoption, null, this);
            String img = "";
            if (mProductBean.getBanner_images_src() != null && mProductBean.getBanner_images_src().size() > 0) {
                img = mProductBean.getBanner_images_src().get(0);
            }
            // 设置默认数据
            mBottomSheetDialog.setDefaultData(img, mProductBean.getMin_price(), mProductBean.getMax_price(), mProductBean.getMin_purchase_gold(),
                    mProductBean.getMax_purchase_gold(), mProductBean.getMin_market_price(),
                    mProductBean.getMax_market_price(), mProductBean.getMin_gold(), mProductBean.getInventory());
        }
        mBottomSheetDialog.showDialog(showType);
    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
    }

    @Override
    public void showErrorView(String msg) {
        showErrorView(msg, ltip_product_details);
        ltip_product_details.setOnReloadListener(view -> {
            ltip_product_details.setLoadingTip(LoadingTip.LoadStatus.loading);
            fetchProductinfo();
        });
    }

    @Override
    public void onProductDetails(ProductBean xnProductBean) {
        srf_pull_product_data.finishRefresh();
        mBottomSheetDialog = null;
        if (xnProductBean == null) {
            ltip_product_details.setLoadingTip(LoadingTip.LoadStatus.error);
            ltip_product_details.setTips("此商品已下架");
        } else {
            ltip_product_details.setLoadingTip(LoadingTip.LoadStatus.finish);
            this.mProductBean = xnProductBean;
            ll_shop_product_collect.setVisibility(mProductBean.getGift_flag() == 1 ? View.GONE : View.VISIBLE);
            initProductData();
        }
    }

    @Override
    public void onCollectionProduct(String msg, ProductBean productBean) {
        stopProgressDialog();
        showShortToast(productBean.getCollection_flag() == 1 ? "收藏成功" : "取消成功");
        mProductBean.setCollection_flag(productBean.getCollection_flag());
        img_shop_product_collect.setSelected(mProductBean.getCollection_flag() == 1);
    }

    @Override
    public void onAddCartProduct(String msg) {
        bottomDismiss();
        stopProgressDialog();
        showShortToast(msg);
        RxBus.getDefault().postSticky(new ProductCartBus());
    }

    @Override
    public void onProductOption(GoodsOption goodsOption) {
        this.mGoodsoption = goodsOption;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (web_product_details != null) {
            web_product_details.destroy();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (web_product_details != null) {
            web_product_details.onResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (web_product_details != null) {
            web_product_details.onPause();
        }
    }


    @OnClick({R.id.tv_entry_shop, R.id.tv_add_product_cart})
    public void OnClick(View v) {
        if (AntiShake.check(v.getId())) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_entry_shop:
                Bundle bundle = new Bundle();
                bundle.putLong(Constants.INP_SHOP_ID, mProductBean.getStore_id());
                openActivity(ShopInfoActivity.class, bundle);
                break;
            case R.id.tv_add_product_cart:
                showBottomSheetDialog(mProductBean.getGift_flag() == 1 ? 1 : 0); // 礼品商城: 智慧商城
                break;
        }
    }

    @Override
    public void onAddCartClick(SpecBean[] apecsBeas, int num) {
        // 加入购物车
        fetchIdsAttribute(apecsBeas, num);
        selectNum = num;
        postCartProduct();
        setSkuText();
    }

    private void fetchIdsAttribute(SpecBean[] apecsBeas, int num) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = apecsBeas.length; i < length; i++) {
            if (apecsBeas[i] != null) {
                if (TextUtils.isEmpty(sb.toString())) {
                    sb.append(apecsBeas[i].getSpec_id());
                } else {
                    sb.append("," + apecsBeas[i].getSpec_id());
                }
            }
        }
        for (int i = 0; i < mGoodsoption.getOptions().size(); i++) {
            if (mGoodsoption.getOptions().get(i).getSpec_ids().equals(sb.toString())) {
                selectGoods = mGoodsoption.getOptions().get(i);
                selectGoods.setTotal(num);
            }
        }
    }

    @Override
    public void onSubmitOrderClick(SpecBean[] apecsBeas, int num) {
        fetchIdsAttribute(apecsBeas, num);
        postToOrder();
        setSkuText();
    }
}